package com.zahb.qadx.ui.activity;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.github.barteksc.pdfviewer.PDFView;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;

import java.io.File;

public class PdfActivity extends BaseActivity {

    String downUrl = "http://qadx.oss-cn-hangzhou.aliyuncs.com/20210118/1610961687394923.pdf";

    Button btn;
    PDFView pdfView;

    private DownloadManager downloadManager;
    private long downloadId;

  //  public static final String cachePath = "storage/emulated/0/Android/data/com.zahb.qadx/files/qian/";

    public static final String dirType = "qian";


    @Override
    protected int getLayout() {
        return R.layout.activity_pdf;
    }

    @Override
    protected void initViews() {

        btn = findViewById(R.id.btn);
        pdfView = findViewById(R.id.pdfView);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("application/pdf");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 110);
            }
        });

        btn.setVisibility(View.GONE);
        downUrl = getIntent().getStringExtra("data");
        if(TextUtils.isEmpty(downUrl)){
            showBindToast("路径为空");
            return;
        }

        String fileName = downUrl.split(File.separator)[downUrl.split(File.separator).length-1];
        String filePath = getExternalFilesDir(dirType).getPath()+File.separator +fileName;
        Log.v("zzw","fileName "+fileName+ " filePath "+filePath+" File.separator "+File.separator);

        File file = new File(filePath);
        if(file.exists()){
            pdfView.fromFile(file)
                    .load();
        }else{
            showProgressDialog("正在下载中...");
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downUrl));
            request.setDestinationInExternalFilesDir(this, dirType, fileName);
            request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE ) ;
            downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            downloadId = downloadManager.enqueue(request);
            registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }


    }


    //广播监听下载的各个状态
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            DownloadManager.Query query = new DownloadManager.Query();
            //通过下载的id查找
            query.setFilterById(downloadId);
            Cursor cursor = downloadManager.query(query);
            if (cursor.moveToFirst()) {
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Log.d("download","status<==>" + status);
                switch (status) {
                    //下载暂停
                    case DownloadManager.STATUS_PAUSED:
                        break;
                    //下载延迟
                    case DownloadManager.STATUS_PENDING:
                        break;
                    //正在下载
                    case DownloadManager.STATUS_RUNNING:
                        showProgressDialog("正在下载中...");
                        Log.d("download","正在下载");
                        break;
                    //下载完成
                    case DownloadManager.STATUS_SUCCESSFUL:
                        Uri uri =  downloadManager.getUriForDownloadedFile(downloadId);
                        //下载完成更新蓝牙
                        Log.d("download","下载完成 "+uri.toString());
                        hideProgressDialog();
                        pdfView.fromUri(uri)
                                .load();
                        cursor.close();
                        break;
                    //下载失败
                    case DownloadManager.STATUS_FAILED:

                        Log.d("download","下载失败");
                        cursor.close();
//                        ((DeviceInfoActivity) view).unregisterReceiver(receiver);
                        break;
                }
            }
        }
    };

    @Override
    protected int getTitleStringRes() {
        return R.string.pdf;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!= Activity.RESULT_OK){
            return;
        }
        if(110 == requestCode){
            if(data!=null){
                Uri uri = data.getData();
                Log.v("zzw",uri.getPath());
                pdfView.fromUri(uri)
                        .load();
            }
        }
    }




}

